# -*- coding: utf-8 -*-
import json
from rest_framework import views, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django.db import transaction
from rest_framework.response import Response
from utils.save_image import save_image

from myapp.models import WeChatAccount


class UserInfo(views.APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    @transaction.atomic
    def post(self, request):
        params = request.data
        user_info = params.get("userInfo", None)
        params = json.loads(user_info)
        if not user_info:
            return Response({'error': '获取用户信息失败'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            wechat = WeChatAccount.objects.get(user=request.user)
            wechat.nickName = params['nickName']
            wechat.gender = '男' if params['gender'] == 1 else '女'
            wechat.city = params['city']
            wechat.province = params['province']
            wechat.country = params['country']
            wechat.avatarUrl = save_image(params['avatarUrl'], 'avatar')
            wechat.save()
        except wechat.DoesNotExist:
            return Response({'error': '用户信息存储失败'}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'msg': '存储成功'})

    def get(self, request):
        try:
            user = WeChatAccount.objects.filter(user=request.user).values_list()
            print(user)
            return Response({'msg': user})
        except user.DoesNotExist:
            return Response({'error': '查询用户信息失败'}, status=status.HTTP_400_BAD_REQUEST)
